import { ref } from 'vue'
import { UserApi } from './api'
import { ConfigClass } from './config'
import { LoginApi } from '@/view/login/api'
import { ElMessage } from 'element-plus'

export class UserClass {
	configClass: ConfigClass
	baseData = ref()
	total = ref(0)
	public query = ref()
	visible = ref<boolean>(false)
	src = ref()
	userVisible = ref<boolean>(false)
	commonForm
	constructor(commonForm) {
		this.commonForm = commonForm
		this.configClass = new ConfigClass(this)
		this.getList()
	}

	/**
	 * 获取表格配置
	 */
	public getTableConfig() {
		return { ...this.configClass.tableConfig, data: this.baseData.value, total: this.total.value }
	}

	/**
	 * 查询配置
	 */
	public getSearchCol() {
		return this.configClass.searchCol
	}

	/**
	 * 查询
	 */
	public serach(query) {
		this.query.value = query
		this.configClass.tableConfig.pagination.currentPage = 1
		this.getList()
	}
	/**
	 * 获取表格数据
	 */
	public getList() {
		const params = {
			...this.query.value,
			currentPage: this.configClass.tableConfig.pagination.currentPage,
			pageSize: this.configClass.tableConfig.pagination.pageSize
		}
		UserApi.getTable(params).subscribe((res: any) => {
			const { records = [], total = 0 } = res
			this.baseData.value = [...records]
			this.total.value = total
		})
	}
	/**
	 * 删除
	 */
	public delete(id: number) {
		const params = {
			id: id
		}
		UserApi.deleteItem(params).subscribe(() => {
			this.getList()
		})
	}

	/**
	 * 分页查询
	 */
	public onPageChange() {
		this.getList()
	}

	/**
	 * 查看封面
	 */
	public preview(img: string) {
		this.src.value = `http://ikun-pro-ui.fun:3000/static/${img}`
		this.visible.value = true
	}

	/**
	 * 新增用户
	 */
	public add() {
		this.userVisible.value = true
	}

	/**
	 * 新增用户配置
	 */
	public getFormCol() {
		return this.configClass.formCol
	}

	/**
	 * 新增用户的底部按钮
	 */
	public getBtns() {
		return this.configClass.btns
	}

	/**
	 * 取消
	 */
	public cancel() {
		this.userVisible.value = false
	}

	/**
	 * 确认
	 */
	public confirm() {
		this.commonForm.value.validForm().then(() => {
			LoginApi.registry(this.commonForm.value.getFormData()).subscribe(() => {
				this.userVisible.value = false
				ElMessage.success('新增成功')
				this.getList()
			})
		})
	}
}
